package cn.tedu.controller;

import cn.tedu.dao.ProductDao;
import cn.tedu.entity.Product;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@MultipartConfig
@WebServlet(name = "SendServlet",urlPatterns = "/send")
public class SendServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String title = request.getParameter("title");
        String name = request.getParameter("author");
        String intro = request.getParameter("intro");
        String categoryId = request.getParameter("categoryId");

//        System.out.println("title:"+title);
//        System.out.println("title:"+name);
//        System.out.println("title:"+intro);
//        System.out.println("title:"+categoryId);
        //接受上传的文件
        Part part= request.getPart("file");
        //得到上传文件的后缀名;
        String info = part.getHeader("content-disposition");
        System.out.println(info);
        String suffix = info.substring(info.indexOf("."),info.length()-1);
        System.out.println(suffix);
        String fileName = UUID.randomUUID()+suffix;
        SimpleDateFormat f = new SimpleDateFormat("yyyy/MM/dd/");
        //创建当前时间的日期对象
        Date date= new Date();
        String subPath = "images/"+f.format(date);
        System.out.println(subPath);
        //得到Tomcat管辖的完整路径
        String path = request.getServletContext().getRealPath(subPath);
        System.out.println(path);
        //创建文件夹
        new File(path).mkdirs();
        //把上传的文件保存到指定的文件夹里面
        part.write(path+fileName);

        Product product = new Product(0,title,name,intro,
                subPath+fileName,0,0,System.currentTimeMillis(),
                Integer.parseInt(categoryId)
        );

        ProductDao dao = new ProductDao();
        dao.insert(product);

        response.sendRedirect("/home");




    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
